package com.project.controller.web;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.project.common.utils.ExcelUtil;
import com.project.common.utils.MyPageHelper;
import com.project.common.utils.PublicUtils;
import com.project.common.validator.ValidatorUtils;
import com.project.common.validator.group.AddGroup;
import com.project.entity.TeacherInfo;
import com.project.entity.User;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.TeacherInfoService;
import com.project.service.UserService;
import com.project.service.base.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/user")
@Api(description = "用户管理接口",value = "user")
public class UserController extends BaseService {

    @Autowired
    private UserService userService;

    @Autowired
    private TeacherInfoService teacherInfoService;


    /**
     * author:wwh
     * date:2018/3/8
     * function:用户修改密码
     * @param user
     * @return
     */
    @ApiOperation("用户修改密码")
    @PostMapping("/modifyPwd")
    public R modifyPwd(@RequestBody User user){
        User oldUser = userService.findAllById(user.getId());
        if(!userService.validatePassword(oldUser,user.getPassword())){
            return R.error(HttpStatus.SC_METHOD_FAILURE,"原密码不正确");
        }else{
            if(!user.getNewPassword().equals(user.getCheckPassword())){
                return R.error(HttpStatus.SC_CONFLICT,"新密码与确认密码不同");
            }else{
                user.setPassword(user.getNewPassword());
                userService.modify(user);
                return R.ok("密码修改成功");
            }
        }
    }

    @ApiOperation("通过id查找用户")
    @GetMapping("/find/{id}")
    public R findUserById(@PathVariable Integer id){
        User user = userService.findById(id);
        return R.ok().put("user",user);
    }

    /**
     * wwh  2018/1/18
     * 批量条件查找
     * @param user
     * @return
     */
    @ApiOperation("条件查询，包括关键词模糊搜索")
    @PostMapping("/findBatchByCondition")
    public R findBatchByCondition(@RequestBody User user){
        ResponseBean responseBean = new ResponseBean();
        try{
            System.out.println(JSON.toJSONString(user));
            List<User> userList = userService.findBatchByCondition(user);
            return R.ok("查找成功").put("data",userList).put("total", MyPageHelper.getTotal(userList));
        }catch(Exception e){
            e.printStackTrace();
            return R.error("查找失败");
        }
    }

    /**
     * wwh 2018/1/25
     * 添加用户
     * @param user
     * @return
     */
    @ApiOperation("添加用户")
    @PostMapping("/add")
    public R addUser(@RequestBody User user) throws Exception{
        try{
            userService.add(user);
            if(user.getUsertype()==1){
                TeacherInfo teacherInfo = new TeacherInfo();
                teacherInfo.setUserid(user.getId());
                teacherInfoService.add(teacherInfo);
            }
            return R.ok("添加成功");
        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * wwh 2018/3/14
     * @param file
     * @param request
     * @return
     */
    @ApiOperation("批量添加用户")
    @PostMapping(value = "/addBatch")
    public R addBatch(@RequestParam(value = "file",required = false) MultipartFile file,HttpServletRequest request) throws IOException{
        try{
            List<User> userList = ExcelUtil.parse(file);
            for(User user : userList){
                if(userService.findByUserName(user.getUsername())==null) {
                    userService.add(user);
                    /**
                     * 需加上学生表和教师表的添加
                     */
                }
            }
            return R.ok();
        }catch(Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }


    /**
     * wwh  2018/3/8
     * 删除单个用户
     * @param id
     * @return
     */
    @ApiOperation("通过id删除单个用户")
    @GetMapping("/remove/{id}")
    public R removeOne(@PathVariable Integer id){
        userService.remove(id);
        return R.ok();
    }

    @ApiOperation("批量删除用户")
    @GetMapping("/removeBatch/{ids}")
    public R removeBatch(@PathVariable String ids){
        List<Integer> idList = new ArrayList<>();
        if(!StringUtils.isEmpty(ids))
            idList = PublicUtils.getIntIdList(ids,",");
        if(idList.size()>0)
            userService.removeBatch(idList);
        return R.ok();
    }

    /**
     *
     * @param user
     * @return
     */
    @ApiOperation("更新用户信息等")
    @PostMapping("/modify")
    public R modify(@RequestBody User user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
        userService.modify(user);
        return R.ok();
    }


//    @ApiOperation("根据筛选条件导出用户Excel")
//    @PostMapping("/exportUsersByCondition")
//    public ResponseEntity<byte[]> exportUsersByCondition(@RequestBody User user, HttpServletResponse response){
//        try {
//            List<User> userList = userService.findBatchByCondition(user);
//            return ExcelUtil.exportExcel(userList, response);
//        }catch (Exception e){
//            e.printStackTrace();
//            return null;
//        }
//    }
}
